package com.canbot.u05.utils;

import android.util.Log;

import com.canbot.u05.activity.presidemode.newcode.bean.NetLoadUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author zmp
 * @date 2017/3/3
 */

public class OkHttpUtils {

    protected static final String TAG = "OkHttpUtils";

    public static OkHttpClient client = new OkHttpClient();

    /**
     * 上传文件
     *
     * @param actionUrl 接口地址
     * @param paramsMap 参数
     * @param callBack  回调
     */
    public static void post(String actionUrl, HashMap<String, ? extends Object> paramsMap, int timeOut, final OkHttpCallBack callBack) {
        try {
            //补全请求地址
            //String requestUrl = "";//String.format("%s/%s", upload_head, actionUrl);
            MultipartBody.Builder builder = new MultipartBody.Builder();
            //设置类型
            builder.setType(MultipartBody.FORM);
            //追加参数
            for (String key : paramsMap.keySet()) {
                Object object = paramsMap.get(key);
                Logger.e(TAG, "file: " + object);
                if (null == object) {
                    continue;
                }
                if (!(object instanceof File)) {
                    builder.addFormDataPart(key, object.toString());
                } else {
                    File file = (File) object;
                    Logger.v(TAG, "key" + key + "file: " + file.getName());
                    String uploadType = "application/*";//二进制
                    if (key.equals("audiofile")) {
                        uploadType = "audio/*";
                    } else if (key.equals("imgfile")) {
                        uploadType = "image/*";
                    }
                    builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(uploadType), file));
                }
            }
            //创建RequestBody
            RequestBody body = builder.build();
            //创建Request
            final Request request = new Request.Builder().url(actionUrl).post(body).build();
            //单独设置参数 比如读取超时时间
            final Call call = client.newBuilder().writeTimeout(timeOut, TimeUnit.SECONDS).connectTimeout(timeOut, TimeUnit.SECONDS).readTimeout(timeOut, TimeUnit.SECONDS).build().newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "onFailure ----->" + e.toString());
                    if (callBack != null) {
                        callBack.onFailure();
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.e(TAG, "response1 ----->" + response.isSuccessful());
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.e(TAG, "response2 ----->" + string);
                        if (callBack != null) {
                            callBack.onSuccess(string);
                        }
                    } else {
                        if (callBack != null) {
                            callBack.onFailure();
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "response3 ----->" + e.toString());
            if (callBack != null) {
                callBack.onFailure();
            }
        }
    }

    /**
     * 上传文件
     *
     * @param actionUrl 接口地址
     * @param paramsMap 参数
     * @param callBack  回调
     */
    public static void post(String actionUrl, HashMap<String, ? extends Object> paramsMap, final OkHttpCallBack callBack) {
        try {
            //补全请求地址
            //String requestUrl = "";//String.format("%s/%s", upload_head, actionUrl);
            MultipartBody.Builder builder = new MultipartBody.Builder();
            //设置类型
            builder.setType(MultipartBody.FORM);
            //追加参数
            for (String key : paramsMap.keySet()) {
                Object object = paramsMap.get(key);
                builder.addFormDataPart(key, object.toString());
            }
            //创建RequestBody
            RequestBody body = builder.build();
            //创建Request
            final Request request = new Request.Builder().url(actionUrl).post(body).build();
            //单独设置参数 比如读取超时时间
            int timeOut = NetLoadUtil.TIMEOUT;
            final Call call = client.newBuilder().writeTimeout(timeOut, TimeUnit.SECONDS).connectTimeout(timeOut, TimeUnit.SECONDS).readTimeout(timeOut, TimeUnit.SECONDS).build().newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "response ----->" + e.toString());
                    if (callBack != null) {
                        callBack.onFailure();
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.e(TAG, "response ----->" + string);
                        if (callBack != null) {
                            callBack.onSuccess(string);
                        }
                    } else {
                        if (callBack != null) {
                            callBack.onFailure();
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            if (callBack != null) {
                callBack.onFailure();
            }
        }
    }

    /**
     * 上传文件
     *
     * @param actionUrl 接口地址
     * @param paramsMap 参数
     * @param callBack  回调
     */
    public static void upLoadFile(String actionUrl, HashMap<String, ? extends Object> paramsMap, final OkHttpCallBack callBack) {
        try {
            //补全请求地址
            //String requestUrl = "";//String.format("%s/%s", upload_head, actionUrl);
            MultipartBody.Builder builder = new MultipartBody.Builder();
            //设置类型
            builder.setType(MultipartBody.FORM);
            //追加参数
            for (String key : paramsMap.keySet()) {
                Object object = paramsMap.get(key);
                Logger.e(TAG, "file: " + object);
                if (null == object) {
                    continue;
                }
                if (!(object instanceof File)) {
                    builder.addFormDataPart(key, object.toString());
                } else {
                    File file = (File) object;
                    Logger.v(TAG, "key" + key + "file: " + file.getName());
                    String uploadType = "application/*";//二进制
                    if (key.equals("audiofile")) {
                        uploadType = "audio/*";
                    } else if (key.equals("imgfile")) {
                        uploadType = "image/*";
                    }
                    builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(uploadType), file));
                }
            }
            //创建RequestBody
            RequestBody body = builder.build();
            //创建Request
            final Request request = new Request.Builder().url(actionUrl).post(body).build();
            //单独设置参数 比如读取超时时间
            final Call call = client.newBuilder().writeTimeout(500, TimeUnit.SECONDS).connectTimeout(500, TimeUnit.SECONDS).readTimeout(500, TimeUnit.SECONDS).build().newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "response ----->" + e.toString());
                    if (callBack != null) {
                        callBack.onFailure();
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.e(TAG, "response ----->" + string);
                        if (callBack != null) {
                            callBack.onSuccess(string);
                        }
                    } else {
                        if (callBack != null) {
                            callBack.onFailure();
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            if (callBack != null) {
                callBack.onFailure();
            }
        }
    }

    // get 请求
    public static void request(String actionUrl, final OkHttpCallBack callBack) {
        Request request = new Request.Builder().url(actionUrl).build();
        Call call = client.newBuilder().writeTimeout(500, TimeUnit.SECONDS).connectTimeout(500, TimeUnit.SECONDS).readTimeout(500, TimeUnit.SECONDS).build().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logger.e(TAG, "response ----->" + e.toString());
                if (callBack != null) {
                    callBack.onFailure();
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    Logger.e(TAG, "response ----->" + string);
                    if (callBack != null) {
                        callBack.onSuccess(string);
                    }
                } else {
                    if (callBack != null) {
                        callBack.onFailure();
                    }
                }
            }
        });
    }

    public static void downloadFile(final String url, final String saveDir, final String name, final OnDownloadListener callBack) {
        Logger.e(TAG, "url=====" + url);
        Request request = new Request.Builder().url(url).build();
        Call call = client.newBuilder().writeTimeout(500, TimeUnit.SECONDS).connectTimeout(500, TimeUnit.SECONDS).readTimeout(500, TimeUnit.SECONDS).build().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logger.e(TAG, "onFailure ----->" + e.toString());
                if (callBack != null) {
                    callBack.onDownloadFailed();
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Logger.e(TAG, "onResponse ----->" + response.toString());
                if (response.isSuccessful()) {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null; // 储存下载文件的目录
                    String savePath = FileUtil.isExistDir(saveDir);
                    try {
                        String file = savePath + "/" + name;
                        is = response.body().byteStream();
                        long total = response.body().contentLength();
                        fos = new FileOutputStream(file);
                        long sum = 0;
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                            sum += len;
                            int progress = (int) (sum * 1.0f / total * 100); // 下载中
                            Logger.e(TAG, "----progress===" + progress);
                            callBack.onDownloading(progress);
                        }
                        fos.flush(); // 下载完成
                        callBack.onDownloadSuccess();
                    } catch (Exception e) {
                        Logger.e(TAG, "1Exception===" + e);
                        callBack.onDownloadFailed();
                    } finally {
                        try {
                            if (is != null) {
                                is.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            if (fos != null) {
                                fos.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    callBack.onDownloadFailed();
                }
            }
        });
    }

    public interface OkHttpCallBack {
        /**
         * 下载成功
         *
         * @param result result
         */
        public void onSuccess(String result);

        /**
         * 下载失败
         */
        public void onFailure();
    }

    public interface OnDownloadListener {

        /**
         * 下载成功
         */
        void onDownloadSuccess();

        /**
         * 下载进度.
         *
         * @param progress * 下载进度
         */
        void onDownloading(int progress);

        /**
         * 下载失败
         */
        void onDownloadFailed();
    }


}
